<template>
    <f7-page>
        <f7-navbar>
            <f7-nav-left>
                <f7-link @click="back">
                    <f7-icon icon="icon-back" style="margin-left:15px;"></f7-icon>
                </f7-link>
            </f7-nav-left>
            <f7-nav-title :title="isAdd ? '新建批次'  :  '修改批次'"></f7-nav-title>
        </f7-navbar>
        <f7-list inline-labels no-hairlines inset>
            <f7-list-item>
                <f7-label>批次名称</f7-label>
                <f7-input type="text" placeholder="请填写" input-style="text-align:right;"
                    :value="form.name" @input="form.name = $event.target.value">
                </f7-input>
            </f7-list-item>
            <f7-list-item id="bidSectionSmartSelect" smart-select v-if="isAdd"
                :smart-select-params="{openIn: 'sheet', closeOnSelect: true, sheetCloseLinkText: '完成'}">
                <f7-label>所属标段</f7-label>
                <select v-model="form.bidSectionId">
                    <option v-for="(bidSectionId, i) in bidSectionIds"
                        :value="bidSectionId" 
                        v-text="$store.state.global.bidSectionMap[bidSectionId].bid_section_name">
                    </option>
                </select>
            </f7-list-item>
            <f7-list-item v-else>
                <f7-label>所属标段</f7-label>
                <span style="text-align:right;" 
                    v-text="$store.state.global.bidSectionMap[batch.bidSectionId].bid_section_name">
                </span>
            </f7-list-item>
            <f7-list-item id="registSmartSelect" smart-select
                :smart-select-params="{openIn: 'page', searchbar: true, searchbarPlaceholder: '搜索', pageBackLinkText: '返回'}">
                <f7-label>检查人</f7-label>
                <select multiple v-model="form.regists">
                    <optgroup label="施工单位">
                        <option v-for="(userId, i) in contractors" :key="userId"
                            :disabled="userId == currentUserId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                    <optgroup label="监理单位">
                        <option v-for="(userId, i) in supervisors" :key="userId"
                            :disabled="userId == currentUserId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                    <optgroup label="建设单位">
                        <option v-for="(userId, i) in constructors" :key="userId"
                            :disabled="userId == currentUserId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                </select>
            </f7-list-item>
            <f7-list-item>
                <f7-label>整改期限</f7-label>
                <f7-stepper :value="form.repairDeadline" :input-readonly="true" :step="1"
                    @stepper:minusclick="form.repairDeadline <= 1 ? 1 : form.repairDeadline--"
                    @stepper:plusclick="form.repairDeadline >= 99 ? 99 : form.repairDeadline++">
                </f7-stepper>
            </f7-list-item>
            <f7-list-item id="chargeSmartSelect" smart-select
                :smart-select-params="{openIn: 'page', closeOnSelect: true, searchbar: true, searchbarPlaceholder: '搜索', pageBackLinkText: '返回', searchbarDisableText: '取消'}">
                <f7-label>负责人</f7-label>
                <select v-model="form.inChargeBy">
                    <optgroup label="施工单位">
                        <option v-for="(userId, i) in contractors" :key="userId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                    <optgroup label="监理单位">
                        <option v-for="(userId, i) in supervisors" :key="userId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                    <optgroup label="建设单位">
                        <option v-for="(userId, i) in constructors" :key="userId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                </select>
            </f7-list-item>
            <f7-list-item id="ccSmartSelect" smart-select
                :smart-select-params="{openIn: 'page', searchbar: true, searchbarPlaceholder: '搜索', pageBackLinkText: '返回'}">
                <f7-label>抄送人</f7-label>
                <select multiple v-model="form.ccs">
                    <optgroup label="施工单位">
                        <option v-for="(userId, i) in contractors" :key="userId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                    <optgroup label="监理单位">
                        <option v-for="(userId, i) in supervisors" :key="userId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                    <optgroup label="建设单位">
                        <option v-for="(userId, i) in constructors" :key="userId"
                            :value="userId" v-text="$store.state.global.userMap[userId].realname">
                        </option>
                    </optgroup>
                </select>
            </f7-list-item>
            <f7-list-item v-if="isOnline">
                <f7-list-button title="提交" style="width:100%;" @click="submit"></f7-list-button>
            </f7-list-item>
        </f7-list>
    </f7-page>
</template>

<script>
import networkEvent from '@/mixins/networkEvent';
import back from '@/mixins/back.js';
import userCategory from '@/mixins/userCategory.js';
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import events from 'events';
import store from '@/store';
import { getUser, setUser, clearUser } from '@/utils/auth';
import { getStore, setStore, clearStore } from '@/utils/storage';
import keys from '@/utils/rememberKeys';
import request from '@/utils/request';
import db from '@/utils/db';

export default {
    mixins: [networkEvent, back, userCategory],
    store: store,
    props: {
        batch: {
        	type: Object
        }
    },
    data: function() {
    	return {
    		isAdd: true,
    		form: {
    			id: '',
    			name: '',
    			bidSectionId: '',
    			regists: [],
    			repairDeadline: 7,
    			inChargeBy: '',
    			ccs: []
    		}
    	};
    },
    methods: {
    	submit: function() {
    		let self = this;
    		let url = '/api/checkQualityBatch/' + (this.isAdd ? 'add' : 'edit');
    		let param = {};
            param.id = self.form.id;
            param.name = self.form.name;
            param.batchType = '安全文明';
            param.bidSectionId = self.form.bidSectionId;
            param.repairDeadline = self.form.repairDeadline;
            param.registIds = self.form.regists;
            param.chargeId = self.form.inChargeBy;
            param.ccIds = self.form.ccs;
            
            let batchId = null;
            request({
                url: url,
                method: 'post',
                data: param
            }).then(data => {
                let element = data.element;
                batchId = element.id;
                return self.isAdd ? 
                    db.insert('tb_checkquality_batch', [element]) : 
                    db.update('tb_checkquality_batch', [element]);
            }).then(() => {
                let promises = [];
                let promise = null;
                promise = Common.executeSql("delete from tb_batch_user where batch_id = ?", [batchId])
                    .then(() => {
                    	return request({
                    	    url: '/api/batchUser/findByCheckQualityBatch',
                    	    method: 'get',
                    	    params: {
                    	        checkQualityBatchId: batchId
                    	    }
                    	});
                    }).then(data => {
                    	let elements = data.list;
                    	return db.insert('tb_batch_user', elements);
                    }).then(() => {
                    	return Promise.resolve();
                    }).catch(error => {
                    	console.error(error);
                    	return Promise.resolve();
                    });
                promises.push(promise);

                promise = Common.executeSql("delete from tb_batch_cc where batch_id = ?", [batchId])
                    .then(() => {
                        return request({
                            url: '/api/batchCc/findByCheckQualityBatch',
                            method: 'get',
                            params: {
                                checkQualityBatchId: batchId
                            }
                        });
                    }).then(data => {
                        let elements = data.list;
                        return db.insert('tb_batch_cc', elements);
                    }).then(() => {
                        return Promise.resolve();
                    }).catch(error => {
                        console.error(error);
                        return Promise.resolve();
                    });
                promises.push(promise);
                
                return Promise.all(promises);
            }).then(() => {
            	self.$f7.dialog.alert('', '提交批次成功！');
                self.$f7.preloader.hide();
                self.$f7router.back();
            }).catch(error => {
                self.$f7.dialog.alert(error.detail.msg, '提交批次失败');
                console.error(error);
                self.$f7.preloader.hide();
            });
    	}
    },
    computed: {
    	bidSectionIds: function() {
    		let bidSectionIds = [];
            for(var bidSectionId in this.$store.state.global.bidSectionMap) {
                if(this.$store.state.global.bidSectionMap[bidSectionId].project_id == getStore(keys.projectIdKey)) {
                    bidSectionIds.push(bidSectionId);
                }
            }
    		return bidSectionIds;
    	},
    	currentUserId: function() {
    		return getUser().userId;
    	}
    },
    watch: {
    	
    },
    created: function() {
    	
    },
    mounted: function() {
        var self = this;
    	if(this.batch == null) {
    		this.form.bidSectionId = this.bidSectionIds[0];
    		this.form.regists.push(this.currentUserId);
            this.form.inChargeBy = this.currentUserId;
    	} else {
            this.isAdd = false;
            this.form.id = this.batch.id;
            this.form.name = this.batch.name;
            this.form.bidSectionId = this.batch.bidSectionId;
            this.form.regists = this.batch.regists;
            this.form.repairDeadline = this.batch.repairDeadline;
            this.form.inChargeBy = this.batch.inChargeBy;
            this.form.ccs = this.batch.ccs;
    	}
        this.$f7.smartSelect.get('#bidSectionSmartSelect .smart-select').setValue(
        	this.$store.state.global.bidSectionMap[this.form.bidSectionId].bid_section_name
        );
        var registNames = this.form.regists.map(function(regist) {
            return self.$store.state.global.userMap[regist].realname;
        });
        this.$f7.smartSelect.get('#registSmartSelect .smart-select').setValue(registNames.join(','));
        this.$f7.smartSelect.get('#chargeSmartSelect .smart-select').setValue(
            this.$store.state.global.userMap[this.form.inChargeBy].realname
        );
        var ccNames = this.form.ccs.map(function(cc) {
            return self.$store.state.global.userMap[cc].realname;
        });
        this.$f7.smartSelect.get('#ccSmartSelect .smart-select').setValue(ccNames.join(','));
    }
}
</script>

<style scoped>

</style>